package com.yand.disk.demo.filter;

import com.yand.disk.demo.config.FileInfoConfig;
import com.yand.disk.demo.entity.Constant;
import com.yand.disk.demo.entity.FileInfoBean;
import com.yand.disk.demo.entity.TDownLink;
import com.yand.disk.demo.service.CheckService;
import com.yand.disk.demo.service.LinkService;
import com.yand.disk.demo.service.NetDiskDispatchService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 对网盘发布的下载链接请求做处理
 */
@WebFilter(filterName = "urlFilter",urlPatterns = {"/s/*"})
public class UrlFilter implements Filter {


    @Autowired
    private CheckService netDiskCheckServiceImpl;


    @Autowired
    private NetDiskDispatchService netDiskDispatchService;


    @Autowired
    private LinkService linkService;



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 对统一的请求进行拦截
     *  过滤器过滤请求的逻辑
     *    1， 对url中s/ 后面的参数全部进行拦截
     *    2， 拦截后的字符串作为链接中的UUID查询该链接的属性
     *    3， 查不到链接信息则跳转404页面
     *    4， 对请求进行 get post 判断
     *         如果是post 且 该链接的属性为 2 （需要输入提取码）则为提取验证码后跳转，这边继续判断传回的提取码与后台的链接中的提取码进行比较
     *             以免有人用postman等工具进行非法获取文件
     *
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        String urlUUID= uri.substring(uri.indexOf("s")+2,uri.length());

        //通过linkcode查询具体的link对象

        TDownLink link =  TDownLink.builder().linkCode(urlUUID).build();
        link = linkService.queryLinkInfoByCode(link);
        /**
         * 这边查询到具体的某一个文件
         *  正常根据 urlUUID 从数据库中读取，这边就从配置文件中获取
         */
        int resultCode = netDiskCheckServiceImpl.check(link,request);

        if(resultCode == Constant.YES){
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            //重定向到其他 过期
            response.sendRedirect(netDiskDispatchService.dispatch(resultCode, urlUUID));
        }


    }





    @Override
    public void destroy() {

    }
}
